package com.ycsj.goldmedalnewconcept.teacher.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Environment;
import android.os.Handler;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.ycsj.common.adapter.ShowPicGvAdapter;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BaseApplication;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.base.SpKeys;
import com.ycsj.common.manager.CustomDialogManager;
import com.ycsj.common.manager.MediaPlayerManager;
import com.ycsj.common.manager.PickChooseManager;
import com.ycsj.common.manager.PopUpManager;
import com.ycsj.common.manager.TimePickerManager;
import com.ycsj.common.utils.DateUtils;
import com.ycsj.common.utils.DeleteFileUtil;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.utils.MaxTextLengthFilter;
import com.ycsj.common.utils.SPUtil;
import com.ycsj.common.utils.SnackbarUtil;
import com.ycsj.common.view.scroll.MyGridView;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.Constants;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.bean.ResultInfo;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.record.RecordingService;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.teacher.adapter.ClassGvAdapter;
import com.ycsj.goldmedalnewconcept.teacher.adapter.WorkGvAdapter;
import com.ycsj.goldmedalnewconcept.teacher.bean.ClassInfo;
import com.ycsj.goldmedalnewconcept.teacher.bean.StudentTel;
import com.ycsj.goldmedalnewconcept.teacher.bean.WorkInfo;
import com.ycsj.goldmedalnewconcept.teacher.utils.ClassUtil;
import com.ycsj.goldmedalnewconcept.view.MyScrollView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPicker;
import me.shaohui.advancedluban.Luban;
import me.shaohui.advancedluban.OnMultiCompressListener;
import okhttp3.Call;

/**
 * 布置练习
 * Created by Administrator on 2019/3/15 0015.
 */

public class TeacherAssignHomeworkActivity extends BaseActivity implements AdapterView.OnItemClickListener {

    //根布局
    @BindView(R.id.ll_main)
    LinearLayout llMain;

    //标题
    @BindView(R.id.tv_title)
    TextView tvTitle;

    //选择班级
    @BindView(R.id.lv_choose_class)
    ImageView lvChooseClass;

    //历史练习
    @BindView(R.id.lv_history)
    ImageView lvHistory;

    //播放按钮
    @BindView(R.id.bt_play)
    Button btPlay;

    //录音按钮
    @BindView(R.id.bt_record)
    Button btRecord;
    //返回
    @BindView(R.id.iv_back)
    ImageView ivBack;
    //展示所有学生的GridView
    @BindView(R.id.mgv)
    MyGridView mgv;
    //打开列表
    @BindView(R.id.tv_show)
    TextView tvShow;
    //展开布局
    @BindView(R.id.ll_show)
    LinearLayout llShow;
    //上次点评练习
    @BindView(R.id.et_last_work)
    EditText etLastWork;
    //上次练习字数
    @BindView(R.id.tv_last_num)
    TextView tv_last_num;
    //本次练习
    @BindView(R.id.et_new_work)
    EditText etNewWork;
    //本次练习字数
    @BindView(R.id.tv_new_num)
    TextView tv_new_num;

    //展示选择图片的GridView
    @BindView(R.id.mgvShowWork)
    MyGridView mgvShowWork;
    //进度条
    @BindView(R.id.playSeekBar)
    SeekBar playSeekBar;
    //录音的时长,初始不显示
    @BindView(R.id.tv_total_time)
    TextView tvTotalTime;

    //提交
    @BindView(R.id.tv_save)
    TextView tvSave;

    //无学生需要显示的空视图
    @BindView(R.id.tv_msg)
    TextView tvMsg;

    //加载布局
    @BindView(R.id.rl_loading)
    RelativeLayout rlLoading;

    //内容布局
    @BindView(R.id.sl_content)
    MyScrollView sl_content;

    //播放录音的整体布局,初始不显示
    @BindView(R.id.ll_play)
    LinearLayout llPlay;

    //标题栏的布局
    @BindView(R.id.ll_title)
    LinearLayout llTitle;

    //发布的时间
    @BindView(R.id.tv_time)
    TextView tvTime;


    //展示学生信息的数据集合
    private List<WorkInfo.ListBean> oldDatas;

    //初次从服务器请求的学生的全部数据
    private List<WorkInfo.ListBean> newDatas;

    //填充适配器的图片地址
    List<String> mPicPaths;

    //展示学生列表的适配器
    private WorkGvAdapter workSutdentGvAdapter;

    //适配对象
    private ShowPicGvAdapter adapter;

    // 上次点评的练习情况
    private String lastContent;

    // 布置的本次练习
    private String newContent;

    //所有班级的列表
    private List<ClassInfo.ListBean> classInfos;

    //展示班级列表的适配器
    private ClassGvAdapter classGvAdapter;

    //记录弹出展示班级列表PopUpWindow的选中位置的值,默认第一个被选中
    private int popSelectedPos = 0;

    //是否获取班级列表数据完成的标识,没完成之前点击选择班级的弹框提示正在加载,不允许点击
    private boolean isLoadClassCompleted;

    //Handler对象
    private Handler handler = new Handler();

    // 上传选中的学生的集合
    private List<StudentTel> stuList;

    //班级ID
    private String userclass;

    //是否开始录音
    private boolean mStartRecording = true;

    //录音结束的标识
    public static final int RECORDOVER = 0x660;

    //是否已经播放
    private boolean hasPlay = false;

    //发布的时间
    private String sendTime;

    @Override
    protected int getContentLayout() {
        return R.layout.activity_teacher_assign_homework;
    }

    @Override
    protected void init() {

        initStateBar();

        //初始化状态
        initState();

        //设置监听
        initListener();

        //设置展示学生列表的GridView
        initGv();

        //初始化录音的触摸事件
        initRecordTouchListener();

        //设置ScrollView的滚动监听
        initScrollViewListener();

        //请求服务器
        httpMethod();
    }

    /**
     * ScrollView的滚动监听
     * 监听滚动距离是为了防止用户按住录音按钮的时候滚动页面到时候不能关闭SerVice
     */
    private void initScrollViewListener() {
        sl_content.setOnScrollListener(new MyScrollView.OnScrollListener() {
            @Override
            public void onScroll(int scrollY) {
                if (scrollY != 0) {
                    //表示滚动了
                    if (!mStartRecording) {
                        onRecord(mStartRecording);
                        mStartRecording = !mStartRecording;
                        //关闭弹框
                        closeRecordPop();
                    }
                }
            }
        });
    }

    /**
     * 初始化状态
     */
    private void initState() {
        //设置SeekBar不可拖动
        playSeekBar.setEnabled(false);
        sl_content.setVisibility(View.GONE);
    }

    /**
     * 设置输入框的长度监听
     */
    @SuppressLint("ClickableViewAccessibility")
    private void initListener() {
        etLastWork.setFilters(new InputFilter[]{new MaxTextLengthFilter(201)});
        etNewWork.setFilters(new InputFilter[]{new MaxTextLengthFilter(201)});

        //输入框的改变监听
        etLastWork.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String inputText = etLastWork.getText().toString().trim();
                if (TextUtils.isEmpty(inputText)) {
                    tv_last_num.setText("0/200");
                } else {
                    if (inputText.length() > 201) {
                        tv_last_num.setText("200/200");
                    } else {
                        tv_last_num.setText(inputText.length() + "/200");
                    }
                }
            }
        });

        etNewWork.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String inputText = etNewWork.getText().toString().trim();
                if (TextUtils.isEmpty(inputText)) {
                    tv_new_num.setText("0/200");
                } else {
                    if (inputText.length() > 501) {
                        tv_new_num.setText("200/200");
                    } else {
                        tv_new_num.setText(inputText.length() + "/200");
                    }
                }
            }
        });

        //设置输入框的触摸事件监听
        etLastWork.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                /*告诉父组件不要拦截他的触摸事件*/
                v.getParent().requestDisallowInterceptTouchEvent(true);
                if (MotionEvent.ACTION_UP == event.getAction()) {
                    /*告诉父组件可以拦截他的触摸事件*/
                    v.getParent().requestDisallowInterceptTouchEvent(false);
                }

                return false;
            }
        });
        etNewWork.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                /*告诉父组件不要拦截他的触摸事件*/
                v.getParent().requestDisallowInterceptTouchEvent(true);
                if (MotionEvent.ACTION_UP == event.getAction()) {
                    /*告诉父组件可以拦截他的触摸事件*/
                    v.getParent().requestDisallowInterceptTouchEvent(false);
                }

                return false;
            }
        });
    }


    /**
     * 初始化展示学生的GridView
     */
    private void initGv() {
        oldDatas = new ArrayList<>();
        workSutdentGvAdapter = new WorkGvAdapter(this, oldDatas,
                R.layout.teacher_item_gb_students);
        mgv.setAdapter(workSutdentGvAdapter);
    }


    /**
     * 请求服务器获取数据
     */
    private void httpMethod() {

        //请求服务器数据获取班级列表
        httpClass();

        //初始化选择相册
        initGvShowPic();
    }

    /**
     * 请求班级里列表数据
     */
    private void httpClass() {
        ClassUtil.httpClass(rlLoading, this, new ClassUtil.onSuccessListener() {
            @Override
            public void onSuccess(List<ClassInfo.ListBean> datas) {
                //回调班级数据
                classInfos = datas;

                //证明有班级
                lvChooseClass.setVisibility(View.VISIBLE);
                lvHistory.setVisibility(View.VISIBLE);

                //改变加载完成的标记
                isLoadClassCompleted = true;

                if (null != classInfos && classInfos.size() != 0) {
                    //加载完班级列表数据后并且设置好列表展示数据后标题栏选择班级弹框可以进行点击了
                    isLoadClassCompleted = true;

                    userclass = classInfos.get(0).getNum() + "";

                    //默认加载第一个班级的数据
                    initMgv(userclass);

                } else {
                    sl_content.setVisibility(View.GONE);
                }
            }

            @Override
            public void hasNoData() {
                //没有班级,不显示顶部的切换班级的按钮和
                lvHistory.setVisibility(View.INVISIBLE);
                lvChooseClass.setVisibility(View.INVISIBLE);
            }
        });
    }


    /**
     * 设置展示学生的MyGridView的适配器
     */
    private void initMgv(String classnum) {

        Map<String, String> map = new HashMap<>();
        map.put("type", "2");
        map.put("ttel", AccountUtils.getAccount(this));
        map.put("num", classnum);
        map.put("platform", "2");
        HttpUtils.post(HttpAddress.CLASSSTUDENT, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtils.showShort(BaseApplication.ERROR);
            }

            @Override
            public void onResponse(String response, int id) {

                WorkInfo info = null;

                try {
                    info = GsonUtil.jsonToBean(response, WorkInfo.class);
                } catch (Exception e) {
                    Log.i("test", "数据解析异常");
                }

                if (null != info) {
                    if ("1".equals(info.getState())) {
                        //返回成功
                        newDatas = info.getList();
                        if (newDatas != null && newDatas.size() != 0) {
                            //证明该班级有学生数据,显示内容布局同时设置界面数据
                            if (sl_content != null && sl_content.getVisibility() != View.VISIBLE) {
                                sl_content.setVisibility(View.VISIBLE);
                            }
                            if (lvHistory != null && lvHistory.getVisibility() != View.VISIBLE) {
                                lvHistory.setVisibility(View.VISIBLE);
                            }
                            if (tvMsg != null && tvMsg.getVisibility() != View.GONE) {
                                tvMsg.setVisibility(View.GONE);
                            }
                            if (rlLoading != null && rlLoading.getVisibility() != View.GONE) {
                                rlLoading.setVisibility(View.GONE);
                            }
                            syncStuData();
                        } else {
                            //没有学生数据,不显示内容布局
                            if (sl_content != null && sl_content.getVisibility() != View.GONE) {
                                sl_content.setVisibility(View.GONE);
                            }
                            //没有学生数据,不显示内容布局
                            if (lvHistory != null && lvHistory.getVisibility() != View.INVISIBLE) {
                                lvHistory.setVisibility(View.INVISIBLE);
                            }
                            if (tvMsg != null && tvMsg.getVisibility() != View.VISIBLE) {
                                tvMsg.setVisibility(View.VISIBLE);
                            }
                            if (rlLoading != null && rlLoading.getVisibility() != View.GONE) {
                                rlLoading.setVisibility(View.GONE);
                            }
                        }

                    } else {
                        //返回错误
                        ToastUtils.showShort("服务器返回异常,状态码是:" + info.getState());
                    }
                } else {
                    Log.i("test", "服务器返回数据为空");
                }
            }
        });
    }

    /**
     * 同步班级列表GridView的选中和没选中的状态
     */
    private void syncClassGvState() {
        for (int i = 0; i < classInfos.size(); i++) {
            if (popSelectedPos == i) {
                classInfos.get(i).setSelected(true);
            } else {
                classInfos.get(i).setSelected(false);
            }
        }
    }

    /**
     * 获取服务器数据后同步学生列表的数据
     */
    private void syncStuData() {

        //清空原有的数据集合
        oldDatas.clear();

        for (int i = 0; i < newDatas.size(); i++) {
            newDatas.get(i).flag = true;
        }

        // 证明有数据
        if (newDatas.size() <= 4) {
            // 如果少于4个学生不需要显示打开列表的提醒按钮
            llShow.setVisibility(View.GONE);
            tvShow.setBackgroundResource(R.drawable.teacher_studentlist_uppull);
            // 小于4个的时候将数据全部添加到oldDatas中
            oldDatas.addAll(newDatas);
        } else {
            // 返回的学生大于4个则显示打开里列表的提醒按钮
            llShow.setVisibility(View.VISIBLE);
            tvShow.setBackgroundResource(R.drawable.teacher_studentlist_downpull);
            for (int i = 0; i < 4; i++) {
                oldDatas.add(newDatas.get(i));
            }
        }
        // 通知适配器刷新数据
        workSutdentGvAdapter.notifyDataSetChanged();
    }

    /**
     * 初始化选择相册的九宫格展示
     */
    private void initGvShowPic() {
        mPicPaths = new ArrayList<>();
        adapter = new ShowPicGvAdapter(this, mPicPaths);
        mgvShowWork.setAdapter(adapter);
        mgvShowWork.setOnItemClickListener(this);
    }

    /**
     * 条目点击事件
     *
     * @param parent
     * @param view
     * @param position
     * @param l
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
        Object itemAdapter = parent.getAdapter();
        if (itemAdapter instanceof ShowPicGvAdapter) {
            if (mPicPaths.size() != 9) {
                if (position == ((ShowPicGvAdapter) itemAdapter).getCount() - 1) {
                    PickChooseManager.startPhotoPickActivity(TeacherAssignHomeworkActivity.this, 9 - mPicPaths.size());
                } else {
                    PickChooseManager.startShowBigActivity(TeacherAssignHomeworkActivity.this, mPicPaths, position);
                }
            } else {
                PickChooseManager.startShowBigActivity(TeacherAssignHomeworkActivity.this, mPicPaths, position);
            }
        }
    }

    /**
     * 请求图库后的回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) {
            if (data != null) {
                ArrayList<String> photos =
                        data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);

                for (int i = 0; i < photos.size(); i++) {
                    mPicPaths.add(photos.get(i));
                }
                //通知适配器刷新
                adapter.notifyDataSetChanged();
            }
        }
    }

    /**
     * 页面控件点击事件
     */
    @OnClick({R.id.bt_play, R.id.lv_history, R.id.lv_choose_class, R.id.tv_show, R.id.tv_save, R.id.iv_back, R.id.ll_choose_time})
    public void onViewClickEvent(View v) {
        switch (v.getId()) {
            case R.id.bt_play:
                //播放录音
                doPlayAudio();
                break;
            case R.id.lv_history:
                //历史练习
                TeacherHistoryHomeWorkActivity.goActivity(this, classInfos.get(popSelectedPos).getNum() + "");
                break;
            case R.id.lv_choose_class:
                //选择班级
                if (isLoadClassCompleted) {
                    //弹出选择班级的PopUpWindow
                    onChoiceClass();
                } else {
                    //没加载完成
                    SnackbarUtil.ShortSnackbar(llMain, "正在加载,请稍候", 0);
                }
                break;
            case R.id.tv_show:
                //全部打开和关闭的操作
                doOpenOrCloseAction();
                break;
            case R.id.tv_save:
                //提交
                doCommitAction();
                break;
            case R.id.iv_back:
                //返回
                finish();
                break;
            case R.id.ll_choose_time:
                //选择时间
                showTimePicker();
                break;

        }
    }

    /**
     * 时间选择器
     */
    private void showTimePicker() {
        TimePickerManager.showPickerHMS(this, new TimePickerManager.onSelectedListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
//                sendTime = DateUtils.getTime(date, "yyyy-MM-dd HH:mm:ss");
                sendTime = DateUtils.getTime(date, "yyyy-MM-dd HH:mm");
                tvTime.setText(sendTime);
            }
        });
    }

    /**
     * 弹窗
     */
    private void onChoiceClass() {

        if (null == classInfos || classInfos.size() == 0) {

            //证明没有班级列表数据,不做任何操作
            return;

        } else {

            PopUpManager.showPop(this, R.layout.teacher_pop_class, 1.0f, llTitle, new PopUpManager.onGetViewListener() {
                @Override
                public void getChildView(View view, int layoutResId) {

                    //展示班级列表的GridView
                    MyGridView gv = view.findViewById(R.id.gv);

                    //第一步:设置默认的选中状态的班级位置
                    syncClassGvState();

                    //第二步:设置列表数据
                    classGvAdapter = new ClassGvAdapter(TeacherAssignHomeworkActivity.this,
                            classInfos, R.layout.teacher_gv_class);

                    gv.setAdapter(classGvAdapter);

                    //第三步:设置点击事件
                    gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {

                            //记录选中的位置
                            popSelectedPos = pos;

                            //同步GridView的状态,设置列表的选中状态
                            syncClassGvState();

                            //通知适配器刷新
                            classGvAdapter.notifyDataSetChanged();

                            //根据当前选中的班级去请求班级小组的数据
                            initMgv(classInfos.get(pos).getNum() + "");

                            //记录当前选择的班级号
                            userclass = classInfos.get(pos).getNum() + "";

                            //延迟关闭弹框
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    PopUpManager.dismiss();
                                }
                            }, 100);
                        }
                    });
                }
            });
        }
    }

    /**
     * 展示显示全部学生列表和收拢学生列表的操作
     */
    private void doOpenOrCloseAction() {
        // 点击打开列表
        if ("打开列表".equals(tvShow.getText())) {
            // GridView显示全部学生数据
            oldDatas.clear();
            oldDatas.addAll(newDatas);
            workSutdentGvAdapter.notifyDataSetChanged();
            tvShow.setText("关闭列表");
            tvShow.setBackgroundResource(R.drawable.teacher_studentlist_uppull);
        } else if ("关闭列表".equals(tvShow.getText())) {
            // GridView只显示4条数据
            oldDatas.clear();
            for (int i = 0; i < 4; i++) {
                oldDatas.add(newDatas.get(i));
            }
            workSutdentGvAdapter.notifyDataSetChanged();
            tvShow.setText("打开列表");
            tvShow.setBackgroundResource(R.drawable.teacher_studentlist_downpull);
        }
    }


    /**
     * 提交的处理
     * 1.判断是否选中学生 2.是否点评了上次练习情况 3.是否布置了本次练习
     */
    private void doCommitAction() {
        if (!isSelect()) {
            ToastUtils.showShort("您还未选择学生");
            return;
        }

        // 上次练习点评
        lastContent = etLastWork.getText().toString().trim();

        // 本次练习
        newContent = etNewWork.getText().toString().trim();
        if (TextUtils.isEmpty(newContent)) {
            ToastUtils.showShort("练习内容为必填项,请填写后再提交");
            return;
        }

        //是否选择了练习图片
//        if (mPicPaths == null || mPicPaths.size() == 0) {
//            ToastUtils.showShort("请选择练习图片");
//            return;
//        }


        //图片
        if (mPicPaths == null || mPicPaths.size() == 0) {
            //没有图片直接上传
            CustomDialogManager.show(this, "上传中...");
            UploadWork(null, getStudentJson());

        } else {
            //遍历选择的图片进行压缩后进行上传
            //做压缩处理
            CustomDialogManager.show(this, "上传中...");
            List<File> files = new ArrayList<>();
            for (int i = 0; i < mPicPaths.size(); i++) {
                File file = new File(mPicPaths.get(i));
                files.add(file);
            }

            //使用Luban做压缩图片处理
            Luban.compress(this, files).setMaxSize(150).setMaxHeight(1280).setMaxWidth(720).putGear(Luban.CUSTOM_GEAR).launch(new OnMultiCompressListener() {

                @Override
                public void onStart() {
                    //压缩开始
                }

                @Override
                public void onSuccess(List<File> fileList) {
                    //压缩成功后的回调,上传该集合的文件
                    UploadWork(fileList, getStudentJson());
                }

                @Override
                public void onError(Throwable e) {
                    //压缩错误
                }
            });
        }
    }

    /**
     * 发布练习
     */
    private void UploadWork(List<File> fileList, String json) {

        PostFormBuilder builder = OkHttpUtils.post().url(HttpAddress.HOMEWORK);

        Map<String, String> map = new HashMap<>();
        map.put("type", "1");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("role", AccountUtils.getRole(this));
        map.put("apptoken", AccountUtils.getToken(this));
        map.put("studentids", json);
        map.put("userclass", userclass);

        //获取系统当前时间格式化为yyyy-MM-dd HH:mm:ss
        if (!TextUtils.isEmpty(sendTime)) {
            //指定时间发布
            map.put("sendtime", sendTime);
        } else {
            //立即发布
            map.put("sendtime", "");
        }

        map.put("content", newContent);
        map.put("comment", lastContent);
        map.put("platform", "2");

        //音频文件
        String audioPath = SPUtil.getString(TeacherAssignHomeworkActivity.this, SpKeys.RECORDAUDIOPATH);

        if (!TextUtils.isEmpty(audioPath) && getTotalDuation() > 1000) {
            //有音频并且音频的时间大于1秒才上传

            map.put("audio_len", getTotalTime() + "");

            File file = new File(audioPath);

            builder.addFile("audio", file.getName(), file);
        }

        LogUtils.iTag("test", "上传的学生JSON是:" + map.toString());

        builder.params(map);

        //图片
        if (fileList != null && fileList.size() != 0) {
            //有文件
            Map<String, File> fileMap = new HashMap<>();
            if (fileList != null && fileList.size() != 0) {
                for (int i = 0; i < fileList.size(); i++) {
                    fileMap.put(System.currentTimeMillis() + i + i + ".jpg", fileList.get(i));
                }
            }
            builder.files("picture", fileMap);
        }

        builder.build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtils.showShort("服务器异常,上传失败");
                CustomDialogManager.dissmiss();
            }

            @Override
            public void onResponse(String response, int id) {
                CustomDialogManager.dissmiss();
                if (!TextUtils.isEmpty(response)) {
                    ResultInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, ResultInfo.class);
                    } catch (Exception e) {
                        LogUtils.iTag("test", Constants.PARSEDATAERROR);
                    }

                    if (null != info) {
                        if ("200".equals(info.state)) {
                            ToastUtils.showShort("练习布置成功");
                            //跳转到历史练习界面
                            TeacherHistoryHomeWorkActivity.goActivity(TeacherAssignHomeworkActivity.this, classInfos.get(popSelectedPos).getNum() + "");
                            finish();
                        } else {
                            ToastUtils.showShort("上传失败,异常码是:" + info.state);
                        }
                    }
                }
            }
        });
    }


    /**
     * 获取选中学生数据
     */
    private String getStudentJson() {
        stuList = new ArrayList<>();
        for (int i = 0; i < newDatas.size(); i++) {
            if (newDatas.get(i).flag) {
                StudentTel stel = new StudentTel();
                stel.setSttel(newDatas.get(i).getSttel());
                stuList.add(stel);
            }
        }

        //转化json
        String json = GsonUtil.listToJson(stuList);

        return json;
    }

    /**
     * 判断老师是否选中了学生的方法 返回值true表示有选择学生,false表示没有选择学生
     *
     * @return
     */
    private boolean isSelect() {
        boolean res = false;
        if (newDatas != null) {
            for (int i = 0; i < newDatas.size(); i++) {
                if (newDatas.get(i).flag) {
                    res = true;
                    break;
                }
            }
        }
        return res;
    }

    /**
     * 录音按钮的触摸事件
     */
    private void initRecordTouchListener() {
        btRecord.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (MediaPlayerManager.getInstance().getPlayer() != null && MediaPlayerManager.getInstance().getPlayer().isPlaying()) {
                    //播放器是播放状态不接受事件
                    return false;
                } else {
                    switch (motionEvent.getAction()) {
                        case MotionEvent.ACTION_DOWN:

                            //隐藏播放的线性布局
                            llPlay.setVisibility(View.INVISIBLE);

                            //弹框
                            showRecordPop();
                            onRecord(mStartRecording);
                            mStartRecording = !mStartRecording;

                            playSeekBar.setProgress(0);

                            //重置播放状态为未播放
                            hasPlay = false;

                            //把播放器置空
                            MediaPlayerManager.getInstance().stop();

                            break;
                        case MotionEvent.ACTION_UP:
                            onRecord(mStartRecording);
                            mStartRecording = !mStartRecording;
                            //关闭弹框
                            closeRecordPop();
                            break;
                    }

                    //返回true表示自己处理模式事件
                    return true;

                }
            }
        });
    }


    /**
     * 处理录音结束的事件
     * <p>
     * 修改代码
     * 111
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);


        if (busInfo != null && busInfo.type == RECORDOVER) {
            //如果录音文件的时长小于1秒则不显示播放布局
            if (getTotalDuation() < 1000) {

                ToastUtils.showShort("录音时长小于1秒,请重新录音");
            } else {
                //显示播放的线性布局
                llPlay.setVisibility(View.VISIBLE);
                //设置显示音频时长的TextView
                tvTotalTime.setText(getTotalTime() + "秒");
            }
        }
    }


    /**
     * 根据音频文件时长
     */
    private int getTotalDuation() {
        int fileDuraiton = 0;
        //设置显示音频时长的TextView
        String audioPath = SPUtil.getString(TeacherAssignHomeworkActivity.this, SpKeys.RECORDAUDIOPATH);
        fileDuraiton = MediaPlayerManager.getSdCardDuration(TeacherAssignHomeworkActivity.this, audioPath);
        return fileDuraiton;
    }

    /**
     * 根据音频文件获取时长并转换为0.00秒显示
     */
    private String getTotalTime() {
        //设置显示音频时长的TextView
        String audioPath = SPUtil.getString(TeacherAssignHomeworkActivity.this, SpKeys.RECORDAUDIOPATH);
        int fileDuraiton = MediaPlayerManager.getSdCardDuration(TeacherAssignHomeworkActivity.this, audioPath);
        StringBuffer sb = new StringBuffer();
        //设置录音总时间TextView的显示
        if (fileDuraiton != 0) {
            int second = fileDuraiton / 1000;//获取秒
            int l = fileDuraiton % 1000; //获取余数
            sb.append(second);
            sb.append(".");
            String mm = String.valueOf(l);
            if (mm.length() > 2) {
                sb.append(mm.substring(0, 2));
            } else {
                sb.append(mm);
            }
//            sb.append("秒");
        }
        return sb.toString();
    }

    /**
     * 关闭录音弹框
     */
    private void closeRecordPop() {
        PopUpManager.dismiss();
    }

    /**
     * 关闭录音对话框
     * 弹出录音对话框
     */
    private void showRecordPop() {
        PopUpManager.showPop(this, R.layout.item_record_pop, 0.3f, this, null);
    }


    /**
     * 录音的方法
     *
     * @param start
     */
    private void onRecord(boolean start) {
        //开启录音的Service
        Intent intent = new Intent(this, RecordingService.class);
        if (start) {
            //播放录音
            btRecord.setBackgroundResource(R.drawable.ic_media_stop);

            File folder = new File(Environment.getExternalStorageDirectory() + "/SoundRecorder");
            if (!folder.exists()) {
                //不存在创建
                //folder /SoundRecorder doesn't exist, create the folder
                folder.mkdir();
            }

            //删除上次的录音文件
            String lastRecordFilePath = SPUtil.getString(TeacherAssignHomeworkActivity.this, SpKeys.RECORDAUDIOPATH);
            if (!TextUtils.isEmpty(lastRecordFilePath)) {
                File file = new File(lastRecordFilePath);
                //如果这个文件是存在的,删除
                if (file.exists() && file.isFile()) {
                    file.delete();
                }
            }

            //启动Service
            startService(intent);

        } else {
            //停止录音
            btRecord.setBackgroundResource(R.drawable.record);
            //关闭Service
            stopService(intent);
        }
    }

    /**
     * 播放录音
     */
    private void doPlayAudio() {

        if (null != MediaPlayerManager.getInstance().getPlayer() && MediaPlayerManager.getInstance().getPlayer().isPlaying()) {

            //播放状态下点击,播放器暂停
            MediaPlayerManager.getInstance().getPlayer().pause();

            //handler不继续发送更新seekbar的消息
            handler.removeCallbacksAndMessages(null);

            btPlay.setBackgroundResource(R.drawable.play);

            //handler不继续发送更新seekbar的消息
            handler.removeCallbacksAndMessages(null);

        } else {
            if (hasPlay) {
                //暂停状态下点击播放
                MediaPlayerManager.getInstance().getPlayer().start();
                btPlay.setBackgroundResource(R.drawable.pause);
                startTime();
            } else {
                //未播放下点击播放
                //改变状态值
                hasPlay = true;

                btPlay.setBackgroundResource(R.drawable.pause);

                //获取录音的文件地址
                String audioPath = SPUtil.getString(this, SpKeys.RECORDAUDIOPATH);

                MediaPlayerManager.getInstance().playSdCardFile(this, audioPath, new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mediaPlayer) {
                        playSeekBar.setMax(mediaPlayer.getDuration());
                    }
                }, new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        btPlay.setBackgroundResource(R.drawable.play);
                        MediaPlayerManager.getInstance().stop();
                        handler.removeCallbacksAndMessages(null);
                        playSeekBar.setProgress(0);
                        hasPlay = false;
                    }
                }, new MediaPlayer.OnErrorListener() {
                    @Override
                    public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                        btPlay.setBackgroundResource(R.drawable.play);
                        MediaPlayerManager.getInstance().stop();
                        handler.removeCallbacksAndMessages(null);
                        hasPlay = false;
                        playSeekBar.setProgress(0);
                        return false;
                    }
                });

                //更新进度条
                startTime();
            }
        }
    }

    /**
     * 更新进度条
     */
    private void startTime() {
        //Handler实现方法
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //获取播放器的播放进度
                int currentPlayProgress = MediaPlayerManager.getInstance().getPlayer().getCurrentPosition();
                if (currentPlayProgress >= MediaPlayerManager.getInstance().getPlayer().getDuration()) {
                    currentPlayProgress = 0;
                    playSeekBar.setProgress(currentPlayProgress);
                } else {
                    playSeekBar.setProgress(currentPlayProgress);
                }
                handler.postDelayed(this, 50);
            }
        }, 50);
    }

    /**
     * 释放资源
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();

        //把保存的音频文件删除掉,防止用户手机内存
        DeleteFileUtil.deleteDirectory("Environment.getExternalStorageDirectory().getAbsolutePath()" + "/SoundRecorder");

        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }

        MediaPlayerManager.getInstance().stop();
    }
}
